<?php
/**
 * Created By kefu_virus_com
 * Author: Virus
 * Date: 2020/2/8
 * Time: 16:27
 */

namespace app\common\auto;

use think\facade\Request;
use app\common\response\Common as CommonResponse;
use think\Response;

class AutoValidate
{
    public function initialize()
    {
        // 验证验证器是否存在
        $class = 'app\\'.MODULE_NAME.'\\validate\\'.CONTROLLER_NAME;
        if (class_exists($class)) {
            // 加载类
            $validate = app($class);
            // 判断类的类型
            if (!$validate instanceof \think\Validate) {
                app(CommonResponse::class)->initialize('不是tp官方的验证类，自动验证失败');
            }
            // 判断是不是post提交数据,允许验证的方法
            if (Request::isPost() && in_array(ACTION_NAME, $validate->allowAction)) {
                // 判断是否有验证场景，根据方法名称自动验证
//                dump($validate->hasScene(ACTION_NAME) === true);die;
                if ($validate->hasScene(ACTION_NAME) === true) {
                    // 直接验证
                    if ($validate->scene(ACTION_NAME)->check(Request::param()) === false) {
                        app(CommonResponse::class)->initialize($validate->getError());
                    }
                } else {
                    // 否则我们走默认的验证
                    if ($validate->check(Request::param()) === false) {
                        app(CommonResponse::class)->initialize($validate->getError());
                    }
                }
            }

            return true;
        } else {
            return true;
        }
    }
}